/** SerialIO.java
 * Utility code interfaces with external microcontroller via the jssc library.
 *-Update 5/17/13: Project change has removed the need for serial communication to an external MC at this time
 *since the project most likely will not be using a physical print/write system. 
 * 
 */

import jssc.*;

public class SerialIO {
	private SerialPort port;
	
	/** Constructor to set up a port with custom settings for the serial port.
	 * @param portName - The local system name of the port to be used (eg, "COM1").
	 * @param baud - The data rate for the port. Common values are 4800,9600, 19200, 38400, 57600,
	 *  115200. Stability best at 9600.
	 * @param dataBits - 
	 * @param stopBits - 
	 * @param parity - 
	 */
	public SerialIO(String portName, int baud, int dataBits, int stopBits, int parity) {
		port = new SerialPort(portName);
		try {
			port.setParams(baud, dataBits, stopBits, parity);
		} catch (SerialPortException e) {
			e.printStackTrace();
		}
	}
	
	/** Constructor to set up the port with default settings. (9600, 8, 1, 0).
	 * @param portName - The local system name of the port to be used (eg, "COM1").
	 */
	public SerialIO(String portName) {
		port = new SerialPort(portName);
		try {
			port.setParams(SerialPort.BAUDRATE_9600, 
			        SerialPort.DATABITS_8,
			        SerialPort.STOPBITS_1,
			        SerialPort.PARITY_NONE);
		} catch (SerialPortException e) {
			e.printStackTrace();
		}
	}
	
	public static String[] getPorts() {
		return SerialPortList.getPortNames();
	}
	
	public boolean openPort() {
		try {
			return port.openPort();
		} catch (SerialPortException e) {
			e.printStackTrace();
		}
		return false; // error condition.
	}
	
	public boolean write(String data) {
		try {
			return port.writeBytes(data.getBytes());
		} catch (SerialPortException e) {
			e.printStackTrace();
		}
		return false; // error condition
	}
	
	
}
